<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form :model="form" ref="formRef" label-width="110px" :rules="rules as FormRules">
      <div class="flex justify-between">
        <div class="w-50%">
          <el-form-item :label="t('supply.name')" prop="name">
            <el-input v-model="form.name" clearable :placeholder="t('supply.name')" />
          </el-form-item>
          <el-form-item :label="t('supply.domain')" prop="domain">
            <el-input v-model="form.domain" clearable :placeholder="t('supply.domain')" />
          </el-form-item>
          <el-form-item :label="t('supply.sup_type')" prop="sup_type">
            <el-select
              v-model="form.sup_type"
              :filterable="true"
              :placeholder="t('supply.sup_type')"
              :clearable="false"
            >
              <el-option
                v-for="item in supTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('supply.phone')" prop="phone">
            <el-input v-model="form.phone" clearable :placeholder="t('supply.phone')" />
          </el-form-item>
          <el-form-item :label="t('supply.email')" prop="email">
            <el-input v-model="form.email" clearable :placeholder="t('supply.email')" />
          </el-form-item>
          <el-form-item :label="t('supply.qq')" prop="qq">
            <el-input v-model="form.qq" clearable :placeholder="t('supply.qq')" />
          </el-form-item>
          <el-form-item :label="t('supply.wechat')" prop="wechat">
            <el-input v-model="form.wechat" clearable :placeholder="t('supply.wechat')" />
          </el-form-item>
          <el-form-item :label="t('supply.whatsapp')" prop="whatsapp">
            <el-input v-model="form.whatsapp" clearable :placeholder="t('supply.whatsapp')" />
          </el-form-item>
          <el-form-item :label="t('supply.dingtalk')" prop="dingtalk">
            <el-input v-model="form.dingtalk" clearable :placeholder="t('supply.dingtalk')" />
          </el-form-item>
        </div>
        <div class="w-50%">
          <el-form-item :label="t('supply.address')" prop="address">
            <el-input v-model="form.address" clearable :placeholder="t('supply.address')" />
          </el-form-item>
          <el-form-item :label="t('supply.tags')" prop="tags">
            <el-input v-model="form.tags" clearable :placeholder="t('supply.tags')" />
          </el-form-item>
          <el-form-item :label="t('supply.owner')" prop="owner">
            <el-select
              v-model="form.owner"
              :filterable="true"
              :placeholder="t('supply.owner')"
              :clearable="false"
            >
              <el-option
                v-for="item in operatorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('supply.partner')" prop="partner">
            <el-select
              v-model="form.partner"
              :filterable="true"
              :placeholder="t('supply.partner')"
              :clearable="false"
              :multiple="true"
            >
              <el-option
                v-for="item in operatorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('supply.att_path')" prop="att_path">
            <!--            <el-input-->
            <!--                v-model="form.att_path"-->
            <!--                clearable-->
            <!--                :placeholder="t('supply.att_path')"-->
            <!--            />-->

            <div class="flex flex-items-center">
              <UploadFile
                url="/common/uploadFile"
                ref="UploadFileRef"
                upload-file-button-name="上传附件"
                :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'word', 'txt']"
                :params="{ directory: 8 }"
                list-type="text"
                :show-file-list="true"
                @upload-success-res="handleUploadCallback"
                @handle-remove-file="handleRemoveFile"
                @handle-picture-card-preview="handlePictureCardPreview"
              />
            </div>
          </el-form-item>
          <el-form-item :label="t('supply.contact')" prop="contact">
            <el-input v-model="form.contact" clearable :placeholder="t('supply.contact')" />
          </el-form-item>
          <el-form-item :label="t('supply.country')" prop="country">
            <el-select
              v-model="form.country"
              :filterable="true"
              :placeholder="t('supply.country')"
              :clearable="false"
            >
              <el-option
                v-for="item in countryList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('supply.remark')" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :autosize="{ minRows: 15, maxRows: 20 }"
              :placeholder="t('supply.remark')"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
  </ContentDetailWrap>
</template>
<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElButton, ElMessage, type FormInstance, FormRules } from 'element-plus'
import { saveDataApi } from '@/api/supply'
import { getEnumApi } from '@/api/supply'
import UploadFile from '@/components/UploadFile/index.vue'
import { createImageViewer } from '@/components/ImageViewer'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const { t } = useI18n()
const { push, go } = useRouter()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  name: '',
  domain: '',
  category: '',
  sup_type: '',
  phone: '',
  email: '',
  qq: '',
  wechat: '',
  whatsapp: '',
  dingtalk: '',
  country: '',
  is_deal: '',
  address: '',
  tags: '',
  owner: '',
  partner: [],
  att_path: [],
  contact: '',
  remark: ''
})

const supTypeList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])
const countryList = ref<Array<Record<string, any>>>([])

const rules = reactive({
  name: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }],
  sup_type: [{ required: true, message: '请选择渠道类型', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]
})

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  form.value.att_path.push(val)
}

const handleRemoveFile = (val: any) => {
  if (form.value.att_path && form.value.att_path.length) {
    form.value.att_path = form.value.att_path.filter(
      (item: Record<string, any>) => item.uploadFile.uid !== val.uid
    )
  }
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val]
  })
}
const getDropDownBoxInfo = async () => {
  form.value.owner = userStore.getUserInfo?.id
  const resp = await getEnumApi({ field: 'all' })
  supTypeList.value = resp.data.sup_type
  operatorList.value = resp.data.operator
  countryList.value = resp.data.country
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    const format_att: number[] = []
    if (Array.isArray(form.value.att_path)) {
      format_att.push(...form.value.att_path.map((item) => item.id))
    } else {
      console.error('att_path is not an array')
    }

    if (valid) {
      const params = {
        name: form.value.name,
        sup_type: form.value.sup_type,
        email: form.value.email,
        owner: form.value.owner,
        partner: form.value.partner,
        att_path: format_att,
        domain: form.value.domain,
        category: 1,
        phone: form.value.phone,
        qq: form.value.qq,
        wechat: form.value.wechat,
        whatsapp: form.value.whatsapp,
        dingtalk: form.value.dingtalk,
        country: form.value.country,
        is_deal: form.value.is_deal,
        address: form.value.address,
        tags: form.value.tags,
        contact: form.value.contact,
        remark: form.value.remark
      } as unknown as Record<string, any>

      const resp = await saveDataApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('supply.createSucMsg'))
        push('/channelManage/supplier/supplierManage')
      }
    }
  })
}

onMounted(() => {
  getDropDownBoxInfo()
})
</script>

<style lang="less" scoped></style>
